package com.sdsy.blockchaintrainingback.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.sdsy.blockchaintrainingback.pojo.user.LoginUser;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author linzili
 * @Date 2023/9/26 11:44
 * @Version 1.0
 */
public class ThreadLocalContextHolder {
    private static final TransmittableThreadLocal<Map<String,Object>> THREAD_LOCAL = new TransmittableThreadLocal() ;

    public static Object get(String key) {
        return getLocalMap().get(key);
    }

    public static void  set(String key,Object value) {
        getLocalMap().put(key,value);
    }

    public static void setLocalMap(Map<String,Object> map) {
        THREAD_LOCAL.set(map);
    }

    public static LoginUser getLoginUser() {
        Map<String, Object> localMap = getLocalMap();
        Long userId = (Long) localMap.get("userId");
        String username = (String)  localMap.get("username");
        LoginUser loginUserDo = new LoginUser(userId, username);
        return  loginUserDo;
    }

    public static void setLoginUser(LoginUser user) {
        Map<String, Object> localMap = getLocalMap();
        localMap.put("userId",user.getUserId());
        localMap.put("username",user.getUsername());
    }

    public static Long getUserId() {
        return getLoginUser().getUserId();
    }

    public static String getUsername() {
        return getLoginUser().getUsername();
    }

    public static void setUserId(Long userId) {
        Map<String, Object> localMap = getLocalMap();
        localMap.put("userId",userId);
    }

    public  static void setUsername(String username) {
        Map<String, Object> localMap = getLocalMap();
        localMap.put("username",username);
    }

    private static Map<String,Object> getLocalMap() {
        if(THREAD_LOCAL.get() == null) {
            THREAD_LOCAL.set(new HashMap<String,Object>());
        }
        return  THREAD_LOCAL.get();
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }
}
